<template>
  <div class="comp-new">
    <el-form ref="newForm" :model="newForm" :label-width="150 + 'px'">
      <el-form-item
        label="设备名称："
        prop="name"
        :rules="[
          { required: true, message: '请输入设备名称', trigger: 'change' },
        ]"
      >
        <el-input placeholder="请输入" v-model.trim="newForm.name"></el-input>
      </el-form-item>
      <el-form-item
        label="设备编号："
        prop="number"
        :rules="[
          { required: true, message: '请输入设备编号', trigger: 'change' },
        ]"
      >
        <el-input placeholder="请输入" v-model.trim="newForm.number"></el-input>
      </el-form-item>
      <el-form-item
        label="设备类型："
        prop="deviceType"
        :rules="[
          { required: true, message: '请选择设备类型', trigger: 'change' },
        ]"
      >
        <el-select
          style="width:100%"
          class="full"
          v-model="newForm.deviceType"
          placeholder="请选择"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, key) in typeList"
            :key="key"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="IP：" prop="ip" :rules="[{ required: true, message: '请输入IP', trigger: 'change' }]">
		    	<el-input placeholder="请输入" v-model.trim="newForm.ip"></el-input>
		  	</el-form-item>
			<el-form-item label="端口：" prop="post" :rules="[{ required: true, message: '请输入端口', trigger: 'change' }]">
		    	<el-input placeholder="请输入" v-model.trim="newForm.post"></el-input>
		  	</el-form-item>
			<el-form-item label="登录用户名：" prop="username" :rules="[{ required: true, message: '请输入登录用户名', trigger: 'change' }]">
		    	<el-input placeholder="请输入" v-model.trim="newForm.username"></el-input>
		  	</el-form-item>
			<el-form-item label="密码：" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'change' }]">
		    	<el-input placeholder="请输入" type="password" v-model.trim="newForm.password"></el-input>
		  	</el-form-item>
			<el-form-item label="通道号：" prop="channelNumber" :rules="[{ required: true, message: '请输入通道号', trigger: 'change' }]">
		    	<el-input placeholder="请输入" v-model.trim="newForm.channelNumber"></el-input>
		  	</el-form-item> -->
      <el-form-item
        label="产品："
        prop="productId"
        :rules="[{ required: true, message: '请选择产品', trigger: 'change' }]"
      >
        <el-select
          class="full"
          v-model="newForm.productId"
          placeholder="请选择"
          @change="onProductChange"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, key) in productList"
            :key="key"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
      v-if="Number(type) < 20"
        label="播放类型："
        prop="playType"
        :rules="[{ required: true, message: '请选择播放类型' }]"
      >
        <el-select class="full" v-model="newForm.playType" placeholder="请选择">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, key) in playTypeList"
            :key="key"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="Number(type) < 20"
        label="产品秘钥："
        prop="productKey"
        :rules="[
          { required: false, message: '请输入产品秘钥', trigger: 'change' },
        ]"
      >
        <el-input
          placeholder="请输入"
          v-model.trim="newForm.productKey"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="型号：" prop="model" :rules="[{ required: true, message: '请输入型号', trigger: 'change' }]">
		    	<el-input placeholder="请输入" v-model.trim="newForm.model"></el-input>
		  	</el-form-item>
			<el-form-item label="平台：" prop="platformId" :rules="[{ required: true, message: '请选择平台', trigger: 'change' }]">
		    	<el-select class="full" v-model="newForm.platformId" placeholder="请选择">
			      	<el-option :label="item.name" :value="item.id" v-for="(item, key) in platformList" :key="key"></el-option>
			    </el-select>
		  	</el-form-item>
			<el-form-item label="功能：" prop="function" :rules="[{ required: true, message: '请选择功能', trigger: 'change' }]">
		    	<el-select class="full" v-model="newForm.function" placeholder="请选择">
			      	<el-option :label="item.name" :value="item.id" v-for="(item, key) in functionList" :key="key"></el-option>
			    </el-select>
		  	</el-form-item> -->
      <el-form-item
        label="安装位置："
        prop="position"
        :rules="[
          { required: true, message: '请输入安装位置', trigger: 'change' },
        ]"
      >
        <el-input
          placeholder="请输入"
          v-model.trim="newForm.position"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="安装人员："
        prop="installperson"
        :rules="[
          { required: false, message: '请输入安装人员', trigger: 'change' },
        ]"
      >
        <el-input
          placeholder="请输入"
          v-model.trim="newForm.installperson"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="安装人员电话："
        prop="installpersonPhone"
        :rules="[
          { required: false, message: '请输入安装人员电话', trigger: 'change' },
        ]"
      >
        <el-input
          placeholder="请输入"
          v-model.trim="newForm.installpersonPhone"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="安装时间："
        prop="installtime"
        :rules="[
          { required: true, message: '请选择安装时间', trigger: 'change' },
        ]"
      >
        <el-date-picker
          v-model="newForm.installtime"
          placeholder="请选择"
          type="date"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="经纬度："
        prop="lon"
        :rules="[
          { required: true, message: '请选择经纬度', trigger: 'change' },
        ]"
      >
        <div class="flex">
          <div class="flex-1 mr-10">
            <el-input
              readonly
              placeholder="经纬度"
              type="text"
              :value="coord"
            ></el-input>
          </div>
          <div>
            <el-button type="green" @click="locateAction">定位</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="设备图片：">
        <el-upload
          class="upload-image"
          :action="config.uploadUrl"
          list-type="picture-card"
          :file-list="fileList"
          accept="image/*"
          :on-success="handleUploadSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :disabled="!$store.getters.hasEditPermission"
          :data="{ token: siteInfos.token }"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="报警电话："
        prop="alarmPhone"
        :rules="[
          { required: false, message: '请输入报警电话', trigger: 'change' },
        ]"
      >
        <el-input
          placeholder="请输入报警电话（多个电话请使用英文逗号隔开）"
          v-model.trim="newForm.alarmPhone"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="视频播放地址："
        prop="videoplayAddrs"
        v-if="Number(type) < 20"
      >
        <!-- <div class="flex">
		  			<div class="flex-1 mr-10">
		  				<el-input placeholder="请输入" v-model.trim="newForm.videoplayAddrs"></el-input>
		  			</div>
		  			<div>
		  				<el-button type="green" @click="newVideoVisible=true">添加</el-button>
		  			</div>
		  		</div> -->
        <div v-for="(item, index) in videos" :key="'video' + index">
          <div class="flex" :class="{ 'mt-20': index > 0 }">
            <div class="flex-1 mr-10">
              <el-input
                placeholder="请输入"
                v-model.trim="videos[index]"
              ></el-input>
            </div>
            <div v-if="index > 0">
              <el-button
                type="danger"
                @click="deleteVideo(item, index)"
                :disabled="!$store.getters.hasEditPermission"
                >删除</el-button
              >
            </div>
            <div v-else>
              <el-button
                type="green"
                @click="newVideoVisible = true"
                :disabled="!$store.getters.hasEditPermission"
                >添加</el-button
              >
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="" v-if="newVideoVisible">
        <div class="flex">
          <div class="flex-1 mr-10">
            <el-input
              class="mr-10"
              placeholder="请输入视频播放地址"
              type="text"
              v-model.trim="newVideo"
            ></el-input>
          </div>
          <div>
            <el-button
              type="green"
              native-type="button"
              @click="confirmNewVideo"
              >确定</el-button
            >
            <el-button
              type="cancel"
              native-type="button"
              @click="newVideoVisible = false"
              >取消</el-button
            >
          </div>
        </div>
      </el-form-item>
      <!-- <div class="flex mb-20" v-if="newVideoVisible">
		  		<div class="el-form-item__label" style="width:150px;"></div>
		  		<div class="flex-1">
		  			
		  			
		  		</div>
		  	</div> -->
      <el-form-item label="备注：">
        <el-input
          placeholder="请输入"
          type="text"
          v-model.trim="newForm.remark"
        ></el-input>
      </el-form-item>
    </el-form>
    <!-- 定位 start -->
    <el-dialog
      v-if="locationModalVisible"
      title="定位"
      :visible.sync="locationModalVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <Location
        :area="unit.areaName"
        ref="location"
        :coord="coord"
        @save="saveLocation"
        @cancel="locationModalVisible = false"
      >
      </Location>
    </el-dialog>
    <!-- 定位 end -->
    <el-dialog
      :visible.sync="previewVisible"
      v-if="previewVisible"
      append-to-body
    >
      <img style="max-width: 100%" :src="previewImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import Location from "@/components/census/record/Location.vue";
export default {
  name: "newEquipment",
  components: {
    Location,
  },
  props: {
    activeData: {
      type: Object,
      default() {
        return null;
      },
    },
    unit: {
      type: Object,
      default() {
        return {};
      },
    },
    type: {
      type: String,
      default: "",
    },
  },
  computed: {
    ...mapState(["siteInfos"]),
    coord() {
      if (this.newForm.lon) {
        return this.newForm.lon + "," + this.newForm.lat;
      }
    },
  },
  watch: {
    activeData() {
      this.initForm();
    },
    fileList(fileList) {
      let urls = fileList.map((item) => item.url);
      this.newForm.img = urls.join(",");
    },
    videos(videoList) {
      if (videoList.length > 1 || videoList[0].length > 0) {
        this.$set(this.newForm, "videoplayAddrs", videoList.join(","));
      } else {
        this.$set(this.newForm, "videoplayAddrs", "");
      }
    },
  },
  data() {
    return {
      newForm: {},
      loading: false,
      functionList: [],
      platformList: [],
      productList: [],
      locationModalVisible: false,
      fileList: [],
      previewImageUrl: "",
      previewVisible: false,
      newVideoVisible: false,
      newVideo: "",
      videos: [""],
      typeList: [],
      playTypeList: [],
    };
  },
  created() {
    // this.getFunction()
    // this.getPlatform()
    this.getProduct();
    this.initForm();
    this.getType();
    // if (this.type == 6 || this.type == 15) {
    this.getPlayType();
    // }
  },
  methods: {
    onProductChange(e) {
      const activeProduct = this.productList.find((item) => item.id == e);
      this.$set(this.newForm, "playType", activeProduct.playType);
    },
    getType() {
      this.$get("/fireFightingIOT/device/deviceTypeList", {
        type: this.type,
      }).then(
        (res) => {
          this.typeList = res.data;
        },
        (err) => {
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    initForm() {
      if (this.activeData) {
        // this.newForm = this.utils.pick(this.activeData,['id','businessId','businessName','deviceClassify','img','lon','lat','name','number','position','ip','post','username','password','channelNumber','model','platformId','function','videoplayAddrs','installtime','productId','alarmPhone','installperson','installpersonPhone','remark']) //Object.assign({},this.activeData)
        this.newForm = this.utils.pick(this.activeData, [
          "id",
          "businessId",
          "businessName",
          "deviceClassify",
          "img",
          "lon",
          "lat",
          "name",
          "number",
          "position",
          "videoplayAddrs",
          "installtime",
          "productId",
          "alarmPhone",
          "installperson",
          "installpersonPhone",
          "remark",
          "deviceType",
          "playType",
          "productKey",
        ]); //Object.assign({},this.activeData)
        let imgList = this.activeData.imgList.map((item, index) => {
          return {
            name: "file" + index,
            url: item,
          };
        });
        this.fileList = imgList;
        if (this.activeData.videoplayAddrList.length > 0) {
          this.videos = [...this.activeData.videoplayAddrList];
        }
      } else {
        this.newForm = {
          businessId: this.unit.id,
          businessName: this.unit.name,
          deviceClassify: this.type,
          img: "",
          lon: "",
          lat: "",
        };
        if (this.$refs["newForm"]) {
          this.$refs["newForm"].resetFields();
        }
      }
    },
    getFunction() {
      this.$get("/fireFightingIOT/device/functionList").then(
        (res) => {
          this.functionList = res.data;
        },
        (err) => {
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    getPlatform() {
      this.$get("/fireFightingIOT/device/platformList").then(
        (res) => {
          this.platformList = res.data;
        },
        (err) => {
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    getProduct() {
      this.$get("/fireFightingIOT/device/productList", {
        type: this.type,
      }).then(
        (res) => {
          this.productList = res.data;
        },
        (err) => {
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    getPlayType() {
      this.$get("/fireFightingIOT/historicalAlarmInfo/dictList", {
        groupname: "播放类型",
      }).then((res) => {
        this.playTypeList = res.data;
      });
    },
    locateAction() {
      this.locationModalVisible = true;
    },
    saveLocation(coord) {
      this.newForm.lon = coord[0];
      this.newForm.lat = coord[1];
      this.locationModalVisible = false;
    },
    handlePictureCardPreview(file) {
      this.previewImageUrl = file.url;
      this.previewVisible = true;
    },
    handleUploadSuccess(res, file) {
      this.fileList.push({ name: res.data.fileName, url: res.data.filePath });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList.map((item) => {
        return { name: item.name, url: item.url };
      });
    },
    confirmNewVideo() {
      if (!this.newVideo) {
        this.$message.error("请输入视频地址");
        return;
      }
      this.videos.push(this.newVideo);
      this.newVideoVisible = false;
      this.newVideo = "";
    },
    deleteVideo(item, index) {
      this.showConfirm("确定删除该视频地址吗？", () => {
        this.videos.splice(index, 1);
        // this.newForm.isDel = '1'
      });
    },
    submitAction() {
      this.$refs["newForm"].validate((valid) => {
        if (valid) {
          this.$emit("submitting");
          this.loading = true;
          let params = Object.assign({}, this.newForm);
          let url = !params.id
            ? "/fireFightingIOT/device/typeAdd"
            : "/fireFightingIOT/device/typeUpdate";
          this.$ajax({
            url: url,
            method: "post",
            data: params,
          }).then(
            (data) => {
              this.loading = false;
              this.$message.success("保存成功");
              this.$emit("success", data);
            },
            (error) => {
              this.loading = false;
              this.$message.error(error.msg);
              this.$emit("fail");
            }
          );
        } else {
          return false;
        }
      });
    },
  },
};
</script>
